package com.qiantu.phone.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.bar.TitleBar;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.qiantu.api.db.HandleListener;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.action.StatusAction;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.event.SceneChangeEvent;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.manager.SceneOperateManager;
import com.qiantu.phone.ui.activity.AddConditionActivity;
import com.qiantu.phone.ui.activity.PanelBindDeviceActivity;
import com.qiantu.phone.ui.activity.PanelBingingActivity;
import com.qiantu.phone.ui.activity.SelectFloorRoomActivity;
import com.qiantu.phone.ui.adapter.RoomManagerSceneAdapter;
import com.qiantu.phone.ui.dialog.AreaSelectDialog;
import com.qiantu.phone.utils.SceneDetailUtil;
import com.qiantu.phone.widget.StatusLayout;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;
import static com.qiantu.api.entity.RoomBean.ROOM_COMMON_SERIALNO;

public class SceneFragment extends AppFragment<AppActivity> implements StatusAction {
    //0 场景操作  1选择场景
    public static final int SCENE_OPERATION = 0;
    public static final int SELECT_SCENE = 1;
    private static final String IS_SELECT_ACT = "isSelectAct";
    private static final String SHOW_FLOOR_ROOM = "showFloorRoom";
    private static final String SELECT_TYPE = "selectType";
    private boolean isSelectAct;
    private boolean showFloorRoom;
    private int selectType;
    private int bingingType;
    private StatusLayout mStatusLayout;
    private TextView selectArea;
    private CheckBox checkbox;
    private RecyclerView sceneList;
//    private View recyclerViewShadow;
    private TextView tvMaxSceneHint;
    private RoomManagerSceneAdapter sceneAdapter;
    private View bottomOperate;
    private View bottomBtn1;
    private View bottomBtn2;
    private View bottomBtn3;
    private ArrayList<SceneBean> selectedScenes = null;
    private TranslateAnimation mShowTranslateAnimation;
    private TranslateAnimation mHideTranslateAnimation;
    private List<String> selectedSceneSerialNos;
    private boolean showMaxSceneHint = false;
    private SceneOperateManager mSceneOperateManager;
    private Map<String,Integer> selectData;

    public SceneFragment() {
    }

    public static SceneFragment newInstance(boolean isSelectAct, boolean showFloorRoom) {
        SceneFragment fragment = new SceneFragment();
        Bundle args = new Bundle();
        args.putBoolean(IS_SELECT_ACT, isSelectAct);
        args.putBoolean(SHOW_FLOOR_ROOM, showFloorRoom);
        fragment.setArguments(args);
        return fragment;
    }

    public static SceneFragment newInstance(boolean isSelectAct, boolean showFloorRoom, int selectType) {
        SceneFragment fragment = new SceneFragment();
        Bundle args = new Bundle();
        args.putBoolean(IS_SELECT_ACT, isSelectAct);
        args.putBoolean(SHOW_FLOOR_ROOM, showFloorRoom);
        args.putInt(SELECT_TYPE, selectType);
        fragment.setArguments(args);
        return fragment;
    }

    public static SceneFragment newInstance(boolean isSelectAct, boolean showFloorRoom, int selectType,int bingingType) {
        SceneFragment fragment = new SceneFragment();
        Bundle args = new Bundle();
        args.putBoolean(IS_SELECT_ACT, isSelectAct);
        args.putBoolean(SHOW_FLOOR_ROOM, showFloorRoom);
        args.putInt(SELECT_TYPE, selectType);
        args.putInt("bingingType", bingingType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isSelectAct = getArguments().getBoolean(IS_SELECT_ACT);
            showFloorRoom = getArguments().getBoolean(SHOW_FLOOR_ROOM);
            selectType = getArguments().getInt(SELECT_TYPE);
            bingingType = getArguments().getInt("bingingType");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_scene;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mStatusLayout = findViewById(R.id.status_layout);
        mStatusLayout.setBackgroundResource(R.drawable.top_round_16dp_secondary_color3);
        selectArea = findViewById(R.id.select_area);
        checkbox = findViewById(R.id.checkbox);
        sceneList = findViewById(R.id.scene_list);
//        recyclerViewShadow = findViewById(R.id.recycler_view_shadow);
        tvMaxSceneHint = findViewById(R.id.tv_max_scene_hint);
        bottomOperate = findViewById(R.id.bottom_operate);
        bottomOperate.setVisibility(View.GONE);
//        recyclerViewShadow.setVisibility(View.GONE);
        bottomBtn1 = findViewById(R.id.btn_belong);
        bottomBtn2 = findViewById(R.id.btn_set_common);
        bottomBtn3 = findViewById(R.id.btn_cancel_common);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        sceneList.setLayoutManager(gridLayoutManager);
        sceneAdapter = new RoomManagerSceneAdapter(getContext())
                .setSelectAct(isSelectAct)
                .setShowFloorRoom(showFloorRoom)
                .setSingleSelect(isSingleSelect)
                .setBingingType(bingingType);
        sceneAdapter.setOnChildClickListener(R.id.checkbox, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                ArrayList<SceneBean> selectedScenes = sceneAdapter.getSelectedData();
                switch (selectType){
                    case SCENE_OPERATION:
                        if (selectedScenes.size() > 0) {
                            showBottomOperateView();
                        } else {
                            hideBottomOperateView();
                        }
                        break;
                    case SELECT_SCENE:
                        tvMaxSceneHint.setText(getString(R.string.max_scene_count_hint, selectedScenes.size()));
                        TitleBar titleBar = getAttachActivity().getTitleBar();
                        if(titleBar != null){
                            if (selectedScenes.size() > 0) {
                                titleBar.getRightView().setEnabled(true);
                            } else {
                                titleBar.getRightView().setEnabled(false);
                            }
                        }
                        break;
                }
            }
        });
        if(showMaxSceneHint){
            sceneAdapter.setMaxSelectCount(5);
            tvMaxSceneHint.setText(getString(R.string.max_scene_count_hint, 0));
            tvMaxSceneHint.setVisibility(View.VISIBLE);
        }
        if(bingingType == 2){
            sceneAdapter.setShowSettingButton(false);
        }
        sceneAdapter.setOnChildClickListener(R.id.setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                SceneDetailUtil.getSceneDetailAndToEdit(SceneFragment.this, getAttachActivity(), sceneAdapter.getData().get(position).getSceneSerialNo());
            }
        });
        sceneAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                SceneBean scene = sceneAdapter.getData().get(position);
                if(bingingType == 2){
                    ((PanelBindDeviceActivity)getActivity()).addScene(sceneAdapter.getItem(position));
                }else{
                    if(mSceneOperateManager == null){
                        mSceneOperateManager = new SceneOperateManager(getContext());
                    }
                    mSceneOperateManager.onClick(itemView, scene.getSceneSerialNo());
                }
            }
        });
        sceneAdapter.setOnChildClickListener(R.id.btn_sort_scene_action,new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                ((PanelBindDeviceActivity)getActivity()).removeData(sceneAdapter.getItem(position).getSceneSerialNo());
                sceneAdapter.getItem(position).setTemporary(null);
                sceneAdapter.notifyItemChanged(position);
            }
        });
        sceneList.setAdapter(sceneAdapter);
        setOnClickListener(selectArea, checkbox, bottomBtn1, bottomBtn2, bottomBtn3);
    }

    public List<SceneBean> getSelectedScenes(){
        if(sceneAdapter != null){
            return sceneAdapter.getSelectedData();
        }
        return null;
    }

    public void setSelectedScenes(List<String> sceneSerialNos){
        if(sceneAdapter != null){
            sceneAdapter.checkSelectedSerialNos(sceneSerialNos);
        }
        selectedSceneSerialNos = sceneSerialNos;
    }

    public void showMaxSceneHint(){
        showMaxSceneHint = true;
        if(tvMaxSceneHint != null && showMaxSceneHint){
            tvMaxSceneHint.setText(getString(R.string.max_scene_count_hint, 0));
            tvMaxSceneHint.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData() {
        List<SceneBean> scenes = LLSceneDBManager.getInstance(getContext()).getAll();
            showComplete();
            if(selectData != null){
                for(SceneBean bean : scenes){
                    if(selectData.get(bean.getSceneSerialNo()) != null){
                        bean.setTemporary(selectData.get(bean.getSceneSerialNo()));
                    }
                }
            }

            sceneAdapter.setTotalData(scenes);
            selectArea.setText(getString(R.string.unlimited_area) + " (" + scenes.size() + ")");
            if(selectedSceneSerialNos != null && selectedSceneSerialNos.size() > 0){
                sceneAdapter.checkSelectedSerialNos(selectedSceneSerialNos);
            }

    }

    private void showEmpty(){
        showEmpty(R.attr.img_emptystate_nosence, R.string.no_set_scene, R.string.add, new StatusLayout.OnBtnClickListener() {
            @Override
            public void onClick(StatusLayout layout) {
                Intent intent = new Intent(getContext(), AddConditionActivity.class);
                intent.putExtra("type", AddConditionActivity.TYPE_SCENE_LINKAGE);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //没获取到数据才再刷新
        if(sceneAdapter.getAllSceneData() == null || sceneAdapter.getAllSceneData().size() == 0){
            initData();
        }
    }

    //刷新选中的房间包含roomSerialNo的场景
    private void refreshData(){
        //选择框还没创建就是不限区域,刷新所有的场景
        if(selectDialog == null){
            initData();
        }else{
            List<SceneBean> scenes = selectDialog.getAllSceneFormSelectArea();
            if(scenes == null || scenes.size() == 0){
                showEmpty();
            }else{
                showComplete();
                sceneAdapter.setTotalData(scenes);
                selectDialog.setTitle(sceneAdapter.getItemCount());
                selectArea.setText(selectDialog.getTitle());
            }
        }
    }

    @Override
    public void onClick(View view) {
        if (view == checkbox) {
            sceneAdapter.setOnlySeeCommonly(checkbox.isChecked());
            String text = (String) selectArea.getText();
            selectArea.setText(text.split(" ")[0] + " (" + sceneAdapter.getItemCount() + ")");
        } else if (view == selectArea) {
            showSelectAreaDialog(selectArea);
        } else if (view == bottomBtn1) {
            List<SceneBean> selectedScenes = sceneAdapter.getSelectedData();
            if(selectedScenes == null || selectedScenes.size() == 0){
                toast(getString(R.string.please_select_scene_hint));
                return;
            }
            Intent intent = new Intent(getContext(), SelectFloorRoomActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            if(selectedScenes != null && selectedScenes.size() == 1){
                intent.putExtra("roomSerialNo", selectedScenes.get(0).getRoomSerialNo());
            }
            startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                @Override
                public void onActivityResult(int resultCode, Intent data) {
                    if (resultCode == RESULT_OK) {
                        String serialNo = data.getStringExtra("serialNo");
                        String roomName = data.getStringExtra("roomName");
                        String floorSerialNo = data.getStringExtra("floorSerialNo");
                        String floorName  = data.getStringExtra("floorName");
                        changeRoom(serialNo, roomName,floorSerialNo,floorName);
                    }
                }
            });
        } else if (view == bottomBtn2) {
            setFavourite(true);
        } else if (view == bottomBtn3) {
            setFavourite(false);
        }
    }

    private void changeRoom(String serialNo, String roomName, String floorSerialNo,String floorName) {
        Map data = new HashMap<>();
        //1房间绑定 2房屋绑定(移除房间,绑定到房屋)
        int linkType = 0;
        if(floorSerialNo.equals(serialNo)){
            linkType = 3;
            data.put("targetSerialNo", floorSerialNo);
        }else if (ROOM_COMMON_SERIALNO.equals(serialNo)) {
            linkType = 2;
            data.put("targetSerialNo", AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
        } else {
            linkType = 1;
            data.put("targetSerialNo", serialNo);
        }
        data.put("type", linkType);
        List<SceneBean> selectedScenes = sceneAdapter.getSelectedData();
        List<String> selectedSerialNos = new ArrayList<>();
        for (SceneBean sceneBean : selectedScenes) {
            selectedSerialNos.add(sceneBean.getSceneSerialNo());
        }
        int finalLinkType = linkType;
        data.put("sceneSerialNoList", selectedSerialNos);
        LLHttpManager.sceneBelong(getViewLifecycleOwner(), data,
                new HttpCallback<HttpData<Void>>((OnHttpListener) getActivity()) {
                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        sceneAdapter.clearSelected();
                        hideBottomOperateView();
                        if (selectedScenes != null && selectedScenes.size() > 0) {
//                            List<String> sceneRooms = new ArrayList<>();
                            for (SceneBean scene : selectedScenes) {
                                //设置RoomSerialNo之前保存,用来更新当前选中的房间下的场景
//                                sceneRooms.add(scene.getRoomSerialNo());
                                if(finalLinkType == 3){
                                    scene.setRoomSerialNo("");
                                    scene.setLinkType(finalLinkType);
                                    scene.setRoomName("");
                                    scene.setFloorName(floorName);
                                    scene.setFloorSerialNo(floorSerialNo);
                                }else{
                                    scene.setRoomSerialNo(serialNo);
                                    scene.setLinkType(finalLinkType);
                                    scene.setRoomName(roomName);
                                    scene.setFloorSerialNo(floorSerialNo);
                                    scene.setFloorName(floorName);
                                }
                                LLSceneDBManager.getInstance(getContext()).put(scene);
                            }
                            toast(R.string.set_success);
                            refreshData();
                            //操作界面，发送刷新事件
                            if(isSelectAct){
                                EventBus.getDefault().post(new RefreshSceneEvent());
                            }
                        }
                    }
                });
    }

    private void setFavourite(boolean isFavourite) {
        selectedScenes = sceneAdapter.getSelectedData();
        List<String> selectedSerialNos = new ArrayList<>();
        for (SceneBean sceneBean : selectedScenes) {
            selectedSerialNos.add(sceneBean.getSceneSerialNo());
        }
        if(selectedSerialNos.size() == 0){
            toast(getString(R.string.please_select_scene_hint));
            return;
        }
        Map<String, Object> data;
        data = new HashMap<>();
        data.put("sceneSerialNoList", selectedSerialNos);
        data.put("isFavourite", isFavourite);
        LLHttpManager.sceneIsFavourite(this, data,
                new HttpCallback<HttpData<Void>>(this) {
                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        sceneAdapter.clearSelected();
                        hideBottomOperateView();
                        if (selectedScenes != null && selectedScenes.size() > 0) {
//                            List<String> sceneRooms = new ArrayList<>();
                            for (SceneBean scene : selectedScenes) {
                                scene.setIsFavourite(isFavourite);
//                                sceneRooms.add(scene.getRoomSerialNo());
                            }
                            LLSceneDBManager.getInstance(getContext()).putInTx(selectedScenes, new HandleListener() {
                                @Override
                                public void onCompleted() {
                                    refreshData();
                                    //操作界面，发送刷新事件
                                    if(isSelectAct){
                                        EventBus.getDefault().post(new RefreshSceneEvent());
                                    }
                                    EventBus.getDefault().post(new UpdateFavouriteEvent(isFavourite ? UpdateFavouriteEvent.TYPE_ADD : UpdateFavouriteEvent.TYPE_CANCEL));
                                }
                            });
                        }
                    }
                });
    }

    AreaSelectDialog selectDialog;

    private void showSelectAreaDialog(View atView) {
        if (selectDialog == null) {
            selectDialog = new AreaSelectDialog(getContext(), AreaSelectDialog.TYPE_SCENE) {
                @Override
                public void onSave(List<SceneBean> result) {
                    sceneAdapter.setTotalData(result);
                    selectDialog.setTitle(sceneAdapter.getItemCount());
                    selectArea.setText(selectDialog.getTitle());
                }
            };
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(DensityUtils.dip2px(getContext(), 0))
                    .offsetY(-DensityUtils.dip2px(getContext(), 50))
                    .asCustom(selectDialog);
        }
        selectDialog.setInitCount(sceneAdapter.getItemCount());
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getNotEmptyRoomFloors();
        floors.remove(0);
        selectDialog.setFloorBeans(floors);
        selectDialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshSceneEvent(RefreshSceneEvent event) {
//        List<String> rooms = new ArrayList<>();
//        rooms.add(event.roomSerialNo);
        refreshData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSceneChangeEvent(SceneChangeEvent event) {
        SceneBean sceneBean = LLSceneDBManager.getInstance(getContext()).getSceneBySerialNo(event.sceneSerialNo);
        sceneAdapter.update(sceneBean);
    }

    private void showBottomOperateView() {
        if (bottomOperate.getVisibility() == View.VISIBLE) {
            return;
        }
        if (mShowTranslateAnimation == null) {
            mShowTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
            mShowTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mShowTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
        }
        bottomOperate.setVisibility(View.VISIBLE);
//        recyclerViewShadow.setVisibility(View.VISIBLE);
        bottomOperate.startAnimation(mShowTranslateAnimation);
    }

    private void hideBottomOperateView() {
        if (bottomOperate.getVisibility() == View.GONE) {
            return;
        }
        if (mHideTranslateAnimation == null) {
            mHideTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
            mHideTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mHideTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
            mHideTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    bottomOperate.setVisibility(View.GONE);
//                    recyclerViewShadow.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        bottomOperate.startAnimation(mHideTranslateAnimation);
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }

    private boolean isSingleSelect = false;
    public void setSingleSelect(boolean value) {
        isSingleSelect = value;
    }

    public void setSortData(String sceneSerialNo,int index){
        for(SceneBean sceneBean : sceneAdapter.getData()){
            if(sceneBean.getSceneSerialNo().equals(sceneSerialNo)){
                sceneBean.setTemporary(""+index);
                sceneAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    public void setSelectData(Map<String,Integer> selectData){
        this.selectData = selectData;
    }
}
